#!/usr/bin/evn python3
# -*- coding: utf-8 -*-
import time,threading
import simpleaudio
from multiprocessing import Process, Queue

class AudioPlay(object):

    def __init__(self,data=None):
        self.mediaData = None
        self.control = None
        if(data!=None):self.mediaData=data

    def play(self,data=None):
        #关闭上次播放的音频
        if(self.control!=None):
            self.stop()
        if(data!=None):self.mediaData=data
        self.control = PlayJob(self.mediaData)

    def stop(self):
        self.control.stop()



# 因为simpleaudio 这个类太坑了，这里只能用进程做控制
class PlayJob(object):
    def __init__(self,data):
        self.mediaData = data
        # 父进程创建Queue，并传给各个子进程：用于通信
        q = Queue()
        self.queue = q
        per_thread = Process(target=self.per,args=(q,))
        per_thread.start()

    def stop(self):
        #改变标志结束播放线程
        self.queue.put_nowait(True)
    # 音频播放线程
    def per(self,q):
        # 播放音频
        control = PlayJob.play_with_simpleaudio(self.mediaData)
        while control.is_playing():
            time.sleep(0.05)
            try:
                #空值就代表继续空值会异常
                stop = q.get_nowait()
            except:
                stop = False
            if(stop):break

    @staticmethod
    def play_with_simpleaudio(seg):
        return simpleaudio.play_buffer(
            seg.raw_data,
            num_channels=seg.channels,
            bytes_per_sample=seg.sample_width,
            sample_rate=seg.frame_rate
        )

